//
//  AccountViewController.m
//  AipuTel
//
//  Created by cretve on 15/1/15.
//  Copyright (c) 2015年 aipu. All rights reserved.
//

#import "AccountViewController.h"
#import "AESCrypt.h"

@interface AccountViewController ()

@property (strong, nonatomic) NSDictionary* userInfo;
@property (copy, nonatomic) NSString* minutes;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *userView;
@property (weak, nonatomic) IBOutlet UIView *loginView;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;

@end

@implementation AccountViewController

- (void)awakeFromNib
{
    self.tabBarItem.title = @"我的账号";
    self.tabBarItem.image = [[UIImage imageNamed:@"account"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBarItem.selectedImage = [[UIImage imageNamed:@"account"] imageWithWhiteMask];
    
    [self autoLogin];
    [self checkVersionInBackground:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"点话通";
    
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UsreInfo" : @{}, @"sessionCookies": [NSData data]}];
    
    NSData* data = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionCookies"];
    if(data.length > 0)
    {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:[NSURL URLWithString:@"http://202.98.133.196/ddserver"] mainDocumentURL:nil];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.userInfo = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"UsreInfo"];
    if(self.userInfo.count > 0)
    {
        _userView.alpha = 1;
        _userView.hidden = NO;
        _loginView.alpha = 1;
        _loginView.hidden = YES;
        
        _phoneLabel.text = _userInfo[@"username"];
        [self showMinutes];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [_tableView reloadData];
}

#pragma mark -

- (IBAction)clickedChange:(UIButton *)sender
{
    [self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"PasswordViewController"] animated:YES];
}

- (IBAction)clickedLogout:(UIButton *)sender
{
    [[AFHTTPRequestOperationManager manager] POST:@"http://202.98.133.196/ddserver/logout" parameters:@{@"userId": _userInfo[@"userId"], @"userSession": _userInfo[@"usersession"]} success:nil failure:nil];
    
    [[NSUserDefaults standardUserDefaults] setObject:@{} forKey:@"UserAccount"];
    [[NSUserDefaults standardUserDefaults] setObject:@{} forKey:@"UsreInfo"];
    [[NSUserDefaults standardUserDefaults] setObject:[NSData data] forKey:@"sessionCookies"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    _loginView.alpha = 0;
    _loginView.hidden = NO;
    _userView.alpha = 1;
    [UIView animateWithDuration:0.3 animations:^{
        _userView.alpha = 0;
        _loginView.alpha = 1;
    } completion:^(BOOL finished) {
        _userView.hidden = YES;
    }];
    
    self.userInfo = nil;
    self.minutes = nil;
    
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (IBAction)clickedLogin:(UIButton *)sender
{
    [self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"] animated:YES];
}

- (IBAction)clickedRegister:(UIButton *)sender
{
    [self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"RegisterViewController"] animated:YES];
}

- (void)autoLogin
{
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAccount": @{}}];
    NSDictionary* dict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"UserAccount"];
    if(dict.count > 0)
    {
        __weak AccountViewController* weakSelf = self;
        [[AFHTTPRequestOperationManager manager] POST:@"http://202.98.133.196/ddserver/login" parameters:@{@"username": dict[@"username"], @"password": [AESCrypt encrypt:dict[@"password"]]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if([responseObject[@"errno"] integerValue] == 0)
            {
                [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"data"] forKey:@"UsreInfo"];
                
                NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://202.98.133.196/ddserver"]]];
                [[NSUserDefaults standardUserDefaults] setObject:cookiesData forKey:@"sessionCookies"];
                
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                weakSelf.userInfo = responseObject[@"data"];
                [weakSelf showMinutes];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            weakSelf.loginView.alpha = 1;
            weakSelf.loginView.hidden = NO;
            weakSelf.userView.alpha = 1;
            weakSelf.userView.hidden = YES;
            
            weakSelf.userInfo = nil;
            weakSelf.minutes = nil;
            
            [weakSelf.tableView reloadData];
        }];
    }
}

- (void)showMinutes
{
    __weak AccountViewController* weakSelf = self;
    [[AFHTTPRequestOperationManager manager] GET:@"http://202.98.133.196/ddserver/getphoneminutes" parameters:@{@"username": _userInfo[@"username"]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if([responseObject[@"errno"] integerValue] == 0)
        {
            weakSelf.minutes = [NSString stringWithFormat:@"%@", responseObject[@"data"][@"minutes"]];
            [weakSelf.tableView reloadData];
        }
    } failure:nil];
}

- (void)checkVersionInBackground:(BOOL)background
{
    if(!background)
    {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"检查新版本...";
    }
    
    __weak AccountViewController* weakSelf = self;
    [[AFHTTPRequestOperationManager manager] GET:@"http://202.98.133.196/ddserver/version" parameters:@{@"os": @"ios"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        
        if([responseObject[@"errno"] integerValue] == 0)
        {
            if([responseObject[@"data"][@"version"] floatValue] > [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] floatValue])
            {
                if([responseObject[@"data"][@"forceupgrade"] isEqualToString:@"Yes"])
                {
                    [UIAlertView bk_showAlertViewWithTitle:@"发现新版本" message:responseObject[@"data"][@"content"] cancelButtonTitle:@"取消" otherButtonTitles:@[@"更新"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                        if(buttonIndex == 0)
                        {
                            exit(0);
                        }
                        else
                        {
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:responseObject[@"data"][@"url"]]];
                        }
                    }];
                }
                else
                {
                    [UIAlertView bk_showAlertViewWithTitle:@"发现新版本" message:responseObject[@"data"][@"content"] cancelButtonTitle:@"取消" otherButtonTitles:@[@"更新"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                        if(buttonIndex == 1)
                        {
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:responseObject[@"data"][@"url"]]];
                        }
                    }];
                }
            }
        }
        else
        {
            [UIAlertView bk_showAlertViewWithTitle:responseObject[@"info"] message:nil cancelButtonTitle:@"好" otherButtonTitles:nil handler:nil];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        [UIAlertView bk_showAlertViewWithTitle:NetworkErrorMessage message:nil cancelButtonTitle:@"好" otherButtonTitles:nil handler:nil];
    }];
}

#pragma mark -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
        return _userInfo.count > 0 ? 2 : 1;
    else
        return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    if(indexPath.section == 0)
    {
        if(indexPath.row == 0)
        {
            cell.textLabel.text = @"手机充值";
            cell.detailTextLabel.text = nil;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        }
        else
        {
            cell.textLabel.text = @"剩余分钟数";
            cell.detailTextLabel.text = _minutes.length > 0 ? _minutes : @"未获取";
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    }
    else
    {
        switch (indexPath.row)
        {
            case 0:
                cell.textLabel.text = @"使用帮助";
                cell.detailTextLabel.text = nil;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.selectionStyle = UITableViewCellSelectionStyleDefault;
                break;
                
            case 1:
                cell.textLabel.text = @"意见反馈";
                cell.detailTextLabel.text = nil;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.selectionStyle = UITableViewCellSelectionStyleDefault;
                break;
                
            case 2:
                cell.textLabel.text = @"最新版本";
                cell.detailTextLabel.text = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
                cell.accessoryType = UITableViewCellAccessoryNone;
                cell.selectionStyle = UITableViewCellSelectionStyleDefault;
                break;
                
            case 3:
                cell.textLabel.text = @"关于";
                cell.detailTextLabel.text = nil;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.selectionStyle = UITableViewCellSelectionStyleDefault;
                break;
                
            default:
                break;
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(indexPath.section == 0)
    {
        if(indexPath.row == 0)
        {
            [self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"RechargeViewController"] animated:YES];
        }
    }
    else
    {
        switch (indexPath.row)
        {
            case 0:
                [self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"HelpViewController"] animated:YES];
                break;
                
            case 1:
                [self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"FeedbackViewController"] animated:YES];
                break;
                
            case 2:
                [self checkVersionInBackground:NO];
                break;
                
            case 3:
                [self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"AboutViewController"] animated:YES];
                break;
                
            default:
                break;
        }
    }
}

@end
